import flask
import os
import json
from concurrent.futures import ThreadPoolExecutor

app = flask.Flask(__name__)


def copy_file(filename, source_dir, target_dir):
    # 拼接文件路径
    source_path = source_dir + os.sep + filename
    target_path = target_dir + os.sep + filename
    # 打开原文件，并获取其中的内容, 然后打开拷贝文件，并写入内容
    print('正在拷贝到', target_path)
    with open(source_path, 'r', encoding='utf8') as source_file:
        with open(target_path, 'w', encoding='utf8') as target_file:
            while True:
                data = source_file.read(1024)
                if data:
                    target_file.write(data)
                else:
                    break
    # return True
    # time.sleep(0.2)


@app.route('/')
def index():
    source_dir = r'D:\Users\asus-pc\Desktop\a'
    multi_thread_dir = r'D:\Users\asus-pc\Desktop\multi_process'
    # 判断拷贝文件路径是否存在，不存在则创建
    if not os.path.exists(multi_thread_dir):
        os.mkdir(multi_thread_dir)
    # 获取需要拷贝文件的文件名
    file_list = os.listdir(source_dir)
    for file_name in file_list:
        multi_thread_pool.submit(copy_file, file_name, source_dir, multi_thread_dir)
    return json.dumps({'res': True})


if __name__ == '__main__':
    multi_thread_pool = ThreadPoolExecutor()
    app.run()
